package com.duxd.springsecurityfinal.springsecurityfinal.security.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author dong
 * @date 2022/1/15 0015
 */
@Component
public class HandlerMethodAnnotationRequestMatcher implements RequestMatcher, InitializingBean {

    public HandlerMethodAnnotationRequestMatcher(RequestMappingHandlerMapping mapping) {
        this.mapping = mapping;
    }

    private Set<String> publicUrl = new HashSet<>();

    RequestMappingHandlerMapping mapping;

    @Override
    public boolean matches(HttpServletRequest request) {
        return publicUrl.contains(request.getRequestURI());
    }

    @Override
    public void afterPropertiesSet()  {
        Assert.isInstanceOf(AuthenticationRequestMappingHandlerMapping.class, this.mapping);
        this.publicUrl = Collections.unmodifiableSet(((AuthenticationRequestMappingHandlerMapping)mapping).getPublicUrl());
        System.out.println("不需要认证的controller handler：" + this.publicUrl);
    }
}
